﻿using System;
using System.Web;

namespace XQT.Cache
{
    /// <summary>
    /// 缓存接口的简单实现
    /// 通过C#提供的HttpRuntime实现
    /// </summary>
    public class HttpCache
    {
        public static bool ExistsKey(string key)
        {
            return Get(key) != null;
        }

        public static void Set(string key, object value)
        {
            HttpRuntime.Cache.Insert(key, value);
        }

        public static void Set(string key, object value, TimeSpan expiry)
        {
            Set(key, value, DateTime.UtcNow.Add(expiry));
        }

        public static void Set(string key, object value, DateTime expiry)
        {
            HttpRuntime.Cache.Insert(key, value, null, expiry, System.Web.Caching.Cache.NoSlidingExpiration);
        }

        public static void Add(string key, object value)
        {
            if (!ExistsKey(key))
                Set(key, value);
        }

        public static void Add(string key, object value, TimeSpan expiry)
        {
            if (!ExistsKey(key))
                Set(key, value, expiry);
        }

        public static void Add(string key, object value, DateTime expiry)
        {
            if (!ExistsKey(key))
                Set(key, value, expiry);
        }

        public static void Replace(string key, object value)
        {
            if (ExistsKey(key))
                Set(key, value);
        }

        public static void Replace(string key, object value, TimeSpan expiry)
        {
            if (ExistsKey(key))
                Set(key, value, expiry);
        }

        public static void Replace(string key, object value, DateTime expiry)
        {
            if (ExistsKey(key))
                Set(key, value, expiry);
        }

        public static object Get(string key)
        {
            return HttpRuntime.Cache[key];
        }

        public static void Delete(string key)
        {
            HttpRuntime.Cache.Remove(key);
        }
    }
}
